package com.goods.user.controller;

import com.goods.entity.User;
import com.goods.user.service.UserService;
import com.goods.utools.mail.Mail;
import com.goods.utools.mail.MailUtils;
import com.goods.utools.verifycode.Verify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

@Controller
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;

    //    原密码验证
    @RequestMapping("/VerifyLoginpass")
    @ResponseBody
    public Boolean verifyLoginpass(String loginpass, HttpSession session) {
//        获取原密码
        User user = (User) session.getAttribute("user");
        String loginpass1 = user.getLoginpass();
//        比较
        if (loginpass.equals(loginpass1)) {
            return true;
        }
        return false;
    }

    //    修改密码
    @RequestMapping("/ChangePassword")
    public String changePassword(HttpSession session, String newpass) {
        User user = (User) session.getAttribute("user");
//        设置新密码
        user.setLoginpass(newpass);
//        数据库更新
        userService.changePwd(user);
//        杀死session
        session.invalidate();
        return "jsps/main";
    }

    //    退出登录
    @RequestMapping("/LoginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "jsps/main";
    }


    //    用户登录验证
    @RequestMapping("/UserLogin")
    public String userLogin(User user, Model model, HttpSession session) {
        User user1 = userService.userLogin(user);
        if (user1 == null) {
            model.addAttribute("loginMsg", "用户名或密码错误");
            return "jsps/user/login";
        } else if (!user1.getStatus()) {
            model.addAttribute("loginMsg", "用户未激活，请到邮箱激活");
            return "jsps/user/login";
        } else {
            session.setAttribute("user", user1);
        }
        return "jsps/main";
    }

    //激活码激活
    @RequestMapping("/UserActivate")
    public String userActivate(
            @RequestParam("activationCode") String activationCode, Model model) {
        User user = new User();
        user.setActivationcode(activationCode);
        Map<String, Object> map = userService.userActivate(user);

        String msg = (String) map.get("msg");
        Boolean status = (Boolean) map.get("status");
        if (status) {
            model.addAttribute("code", "success");
        } else {
            model.addAttribute("code", "error");
        }
        model.addAttribute("msg", msg);

        return "jsps/msg";
    }

    //    生产激活码
    private String createActivationCode() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String uuid2 = UUID.randomUUID().toString().replace("-", "");
        return uuid + uuid2;
    }

    //用户注册
    @RequestMapping("/RegistUser")
    public String registUser(User user, Model model) throws IOException, MessagingException {
//        刚注册的用户是未激活的
        user.setStatus(false);
//        给用户生产激活码
        user.setActivationcode(createActivationCode());
//        插入
        boolean res = userService.registUser(user);
//        发邮件
        Properties properties = new Properties();
//        获取邮件配置信息
        properties.load(this.getClass().getClassLoader().getResourceAsStream("email.properties"));
        String host = properties.getProperty("host");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
//        创建一个会话
        Session session = MailUtils.createSession(host, username, password);
//        生成一个邮件
        String from = properties.getProperty("from");//发送方
        String to = user.getEmail();//接受方
        String subject = properties.getProperty("subject");//标题
        String content = properties.getProperty("content");//内容
        String activationCode = user.getActivationcode();//激活码
        content = MessageFormat.format(content, activationCode);//激活码写入
        Mail mail = new Mail(from, to, subject, content);//写入邮件
        MailUtils.send(session, mail);//发送

//        设置code和msg
        if (res) {
            model.addAttribute("code", "success");
            model.addAttribute("msg", "注册成功");
        } else {
            model.addAttribute("code", "error");
            model.addAttribute("msg", "注册失败");
        }
//        跳转msg.jsp
        return "jsps/msg";
    }


    //校验验证码
    @RequestMapping("/VerifyVeifycode")
    @ResponseBody
    public Boolean verifyVeifycode(HttpSession session, String verifycode) {
        //1 从session中  拿到 正确的验证码的值
        String vCode = (String) session.getAttribute("vCode");
        //2 比较  不区分大小写
        if (vCode.equalsIgnoreCase(verifycode)) {
            return true;
        }
        return false;
    }

    //    校验Email
    @RequestMapping("/VerifyEmail")
    @ResponseBody
    public Boolean verifyEmail(User user) {
        return userService.getUserByCase(user);
    }


    //    验证码获取
    @RequestMapping("/CreatViriyCode")
    public void getViriy(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Verify.getVirify(request, response);
    }

    //校验用户名
    @RequestMapping("/VerifyLoginname")
    @ResponseBody
    public Boolean verifyLoginname(User user) {
        return userService.getUserByCase(user);
    }
}
